package com.jzr.task.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

public class StreamUtil {
    private static final int PROTECTED_LENGTH = 10240000;// 输入流保护 1M

    public static String getString(InputStream input,String charsetName) throws IOException {
        if (input == null) {
            throw new IOException("输入流为null");
        }

        //字节数组
        byte[] bcache = new byte[2048];
        int readSize = 0;//每次读取的字节长度
        int totalSize = 0;//总字节长度
        ByteArrayOutputStream infoStream = new ByteArrayOutputStream();
        try {
            //一次性读取2048字节
            while ((readSize = input.read(bcache)) > 0) {
                totalSize += readSize;
                if (totalSize > PROTECTED_LENGTH) {
                    throw new IOException("输入流超出10M大小限制");
                }
                //将bcache中读取的input数据写入infoStream
                infoStream.write(bcache, 0, readSize);
            }
        } catch (IOException e1) {
            throw new IOException("输入流读取异常");
        } finally {
            try {
                //输入流关闭
                input.close();
            } catch (IOException e) {
                throw new IOException("输入流关闭异常");
            }
        }
        try {
            return infoStream.toString(charsetName);
        } catch (UnsupportedEncodingException e) {
            throw new IOException("输出异常");
        }
    }
    public static String toString(InputStream is) {
        try {
            ByteArrayOutputStream boa=new ByteArrayOutputStream();
            int len=0;
            byte[] buffer=new byte[1024];
            while((len=is.read(buffer))!=-1){
                boa.write(buffer,0,len);
            }
            is.close();
            boa.close();
            byte[] result=boa.toByteArray();

            String temp=new String(result);

//识别编码
            if(temp.contains("utf-8")){
                return new String(result,"utf-8");
            }else if(temp.contains("gb2312")){
                return new String(result,"gb2312");
            }else{
                return new String(result,"utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

}
